package com.shigen.demo.atguigu;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 锁支持demo
 *
 * @author shigenfu
 * @date 2022/5/31 2:44 下午
 */
public class LockSupportDemo {

  static Object objectLock = new Object();
  static Lock lock = new ReentrantLock();
  static Condition condition = lock.newCondition();

  private static void synchronizedWaitNotify() {
    new Thread(() -> {
      try {
        TimeUnit.MILLISECONDS.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      synchronized (objectLock) {
        System.out.println(Thread.currentThread().getName() + "---- come in");
        try {
          objectLock.wait();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "---  被唤醒");
      }
    }, "aa").start();

    new Thread(() -> {
      synchronized (objectLock) {
        System.out.println(Thread.currentThread().getName() + "---- 通知");
        objectLock.notify();
      }
    }, "bb").start();
  }

  public static void lockAwaitSignal() {

    new Thread(() -> {
      try {
        TimeUnit.MILLISECONDS.sleep(100);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      lock.lock();
      try {
        condition.await();
        System.out.println(Thread.currentThread().getName() + "---- come in");
      } catch (InterruptedException e) {
        e.printStackTrace();
      } finally {
        lock.unlock();
      }
    }, "aa").start();

    new Thread(() -> {
      lock.lock();
      try {
        condition.signal();
        System.out.println(Thread.currentThread().getName() + "---- 通知");
      } finally {
        lock.unlock();
      }
    }, "bb").start();
  }


  public static void lockSupportPackUnpack() {
    Thread t1 = new Thread(() -> {
      try {
        TimeUnit.SECONDS.sleep(2);
      } catch (InterruptedException interruptedException) {
        interruptedException.printStackTrace();
      }
      System.out.println(Thread.currentThread().getName() + " ---- come in");

      LockSupport.park();

      System.out.println(Thread.currentThread().getName() + "---- 被唤醒");
    }, "aa");
    t1.start();


    Thread t2 = new Thread(() -> {
      LockSupport.unpark(t1);
      System.out.println(Thread.currentThread().getName() + "---- 通知了");
    }, "bb");
    t2.start();
  }


  public static void main(String[] args) {
    // synchronizedWaitNotify();
    // lockAwaitSignal();
    lockSupportPackUnpack();
  }
}
